<?php
/**
 * Created by 项目.
 * User: xuguopeng
 * Date: 2020-06-16
 * Time: 11:39
 */

namespace app\api\controller\v1;

use app\api\service\Token;
use app\api\model\Address as AddressModel;
use app\api\controller\BaseController;
use app\api\validate\address\CheckAddress;
use app\api\validate\IdMustBePositiveInt;
use think\facade\Request;

class Address extends BaseController
{
    // 获取当前用户的地址列表
    public function getDataList()
    {
        $uid = Token::getCurrentUid();
        return AddressModel::where('user_id',$uid)->order('id desc')->select()->toArray();
    }

    // 获取某条地址详情
    public function getDataInfo($id)
    {
        (new IdMustBePositiveInt())->goCheck();
        $uid = Token::getCurrentUid();
        return AddressModel::where('user_id',$uid)->where('id',$id)->find();
    }

    // 获取默认
    public function getDefault()
    {
        $uid = Token::getCurrentUid();
        $info = AddressModel::where('user_id',$uid)->where('default',1)->find();
        if(!$info) {
            $info = AddressModel::where('user_id',$uid)->find();
        }
        return $info;
    }

    // 修改为默认
    public function updateDefault($id)
    {
        (new IdMustBePositiveInt())->goCheck();
        $uid = Token::getCurrentUid();
        $AddressModel = new AddressModel();
        $AddressModel->allowField(['default'])->save(['default' => 0], ['user_id' => $uid]);
        $address = AddressModel::where('user_id',$uid)->where('id',$id)->find();
        $address->default = 1;
        $address->save();
        return writeJson(201,[],'设置成功');
    }

    // 创建新地址
    public function createData()
    {
        $uid = Token::getCurrentUid();
        $post = Request::post();
        (new CheckAddress())->goCheck();
        if($post['default'] == 1) {
            $AddressModel = new AddressModel();
            $AddressModel->allowField(['default'])->save(['default' => 0], ['user_id' => $uid]);
        }
        $post['user_id'] = $uid;
        if($post['province'] == $post['city']) {
            $post['province'] = '';
        }
        AddressModel::create($post);
        return writeJson(201, [], '添加成功！');
    }

    // 更新新地址
    public function updateData()
    {
        $uid = Token::getCurrentUid();
        $data = Request::put();
        (new CheckAddress())->goCheck();
        if($data['default'] == 1) {
            $AddressModel = new AddressModel();
            $AddressModel->allowField(['default'])->save(['default',0], ['user_id' => $uid]);
        }
        if($data['province'] == $data['city']) {
            $data['province'] = '';
        }
        $mode = new AddressModel();
        $mode->allowField(true)->save($data, [ 'id' => $data['id'] ]);
        return writeJson(202, [], '更新成功！');
    }

    /**
     * 删除信息
     */
    public function deleteData($id)
    {
        (new IdMustBePositiveInt())->goCheck();
        Token::getCurrentUid();
        AddressModel::destroy($id);
        return writeJson(203, [], '删除成功！');
    }
}